<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select
        v-model="listQuery.status"
        style="width: 200px"
        class="filter-item"
        placeholder="请选择类型"
      >
        <el-option v-for="(item, index) in typeMap" :key="index" :label="item.label" :value="item.value" />
      </el-select>
      <el-button
        v-permission="['operation:distributionstrategy:list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getList"
      >查找</el-button>
      <el-button
        v-permission="['operation:distributionstrategy:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="createDialogBtn"
      >添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="80" prop="id" />

      <el-table-column align="center" label="类型" width="100" prop="type">
        <template slot-scope="scope">
          <el-tag >{{ scope.row.type | typeFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="关联Id" width="80" prop="typeId" />

      <el-table-column align="center" label="策略名" prop="title" />

      <el-table-column align="center" label="上级销售抽点策略" prop="mergeType" >
        <template slot-scope="scope">
          <el-tag >{{ scope.row.mergeType === 1 ? '叠加下级抽点' : '取下级最高抽点' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="商品抽点" width="120" prop="radio" >
        <template slot-scope="scope">
          {{ scope.row.radio / 10.0 }}%
        </template>
      </el-table-column>

      <el-table-column align="center" label="一级抽点" width="120" prop="firstRadio" >
        <template slot-scope="scope">
          {{ scope.row.firstRadio / 10.0 }}%
        </template>
      </el-table-column>

      <el-table-column align="center" label="二级抽点" width="120" prop="secondRadio" >
        <template slot-scope="scope">
          {{ scope.row.secondRadio / 10.0 }}%
        </template>
      </el-table-column>

      <el-table-column align="center" label="三级抽点" width="120" prop="thirdRadio" >
        <template slot-scope="scope">
          {{ scope.row.thirdRadio / 10.0 }}%
        </template>
      </el-table-column>

      <el-table-column align="center" width="180" label="创建时间" prop="gmtCreate">
        <template slot-scope="scope">{{ scope.row.gmtCreate | formatTime }}</template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['operation:distribution:edit']"
            type="primary"
            size="mini"
            @click="updateDialogBtn(scope.row)"
          >编辑</el-button>
          <el-button
            v-permission="['operation:distribution:delete']"
            type="danger"
            size="mini"
            @click="deleteDistributionBtn(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        v-loading="diglogLoadding"
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="id" prop="id" hidden>
          <el-input v-model="dataForm.id" />
        </el-form-item>

        <el-form-item v-if="dialogStatus=='create'" label="策略类型" prop="type">
          <el-select
            v-model="dataForm.type"
            style="width: 200px"
            class="filter-item"
            placeholder="请选择策略类型"
          >
            <el-option v-for="(item, index) in typeMap" :key="index" :label="item.label" :value="item.value" />
          </el-select>
          <el-tooltip class="item" effect="dark" content="优先级 商品 > 类目 > 全部" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip>
        </el-form-item>
        <el-form-item v-if="dataForm.type && dataForm.type === 2 && dialogStatus=='create'" label="类目" prop="typeId">
          <el-cascader
            :options="categoryList"
            v-model="categoryIds"
            expand-trigger="hover"
            @change="handleCategoryChange"
          />
        </el-form-item>
        <el-form-item v-if="dataForm.type && dataForm.type === 3 && dialogStatus=='create'" label="商品" prop="typeId">
          <el-select
            v-model="dataForm.typeId"
            :remote-method="searchSpu"
            placeholder="请搜索商品名"
            filterable
            remote
            reserve-keyword
            @change="searchSpuChange">
            <el-option
              v-for="item in keyRes"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="商品总抽点" prop="radio">
          <el-input-number v-model="dataForm.radio" :min="0" :max="100" :step="1" :precision="1"/>
          <el-tooltip class="item" effect="dark" content="从商品中总共拿出 N% 来。作为下面三级代理的佣金。" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip>
        </el-form-item>

        <el-form-item label="一级抽点" prop="firstRadio">
          <el-input-number v-model="dataForm.firstRadio" :min="0" :max="100" :step="1" :precision="1"/>
          <el-tooltip class="item" effect="dark" content="一级代理'商品总抽点'的份额 M%。 该级实际获取佣金为。 佣金 = 商品总价 * N% * M%" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip>
        </el-form-item>

        <el-form-item label="二级抽点" prop="secondRadio">
          <el-input-number v-model="dataForm.secondRadio" :min="0" :max="100" :step="1" :precision="1"/>
        </el-form-item>

        <el-form-item label="三级抽点" prop="thirdRadio">
          <el-input-number v-model="dataForm.thirdRadio" :min="0" :max="100" :step="1" :precision="1"/>
        </el-form-item>

        <el-form-item label="上级售卖" prop="mergeType">
          <el-radio-group v-model="dataForm.mergeType">
            <el-radio :label="1">叠加下级佣金
              <el-tooltip class="item" effect="dark" content="例如：一级抽点为20%，二级抽点为30%，三级抽点50%。若一级代理成功售卖。则叠加二三级抽点。总共抽点：100% = 20% + 30% + 50% (此处100%是指佣金的百分之百，而非商品的百分之百)" placement="top-start">
                <i class="el-icon-question" />
              </el-tooltip>
            </el-radio>

            <el-radio :label="2">取下级最高佣金
              <el-tooltip class="item" effect="dark" content="例如：一级抽点为20%，二级抽点为30%，三级抽点50%。若一级代理成功售卖。则取下级最高点。总共抽点：50%" placement="top-start">
                <i class="el-icon-question" />
              </el-tooltip>
            </el-radio>

          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" :loading="submitting" type="primary" @click="handleCreate">确定</el-button>
        <el-button v-else :loading="submitting" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>

</div></template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { listDistributionStrategy, createDistributionStrategy, deleteDistributionStrategy, updateDistributionStrategy } from '@/api/distribution'
import { searchGoods } from '@/api/goods'
import { categoryTree } from '@/api/category'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import ElOption from '../../../node_modules/element-ui/packages/select/src/option' // Secondary package based on el-pagination

const typeMap = [{
  value: 1,
  label: '全部'
}, {
  value: 2,
  label: '分类'
}, {
  value: 3,
  label: '商品'
}]

export default {
  name: 'DistributionStrategy',
  components: {
    ElOption,
    Pagination
  },
  filters: {
    typeFilter(code) {
      return typeMap[code - 1].label
    }
  },
  data() {
    return {
      uploadPath,
      categoryList: [],
      categoryIds: [],
      list: [],
      keyRes: [],
      searchSpuRes: [],
      total: 0,
      diglogLoadding: false,
      listLoading: true,
      typeMap,
      listQuery: {
        page: 1,
        limit: 20,
        type: undefined
      },
      dataForm: {
        id: undefined,
        type: undefined,
        typeId: undefined,
        radio: undefined,
        firstRadio: undefined,
        secondRadio: undefined,
        thirdRadio: undefined,
        mergeType: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        type: [{ required: true, message: '分销策略类型不能为空', trigger: 'blur' }],
        radio: [{ required: true, message: '商品总抽点', trigger: 'blur' }],
        firstRadio: [{ required: true, message: '一级抽点不能为空', trigger: 'blur' }],
        secondRadio: [{ required: true, message: '二级抽点不能为空', trigger: 'blur' }],
        thirdRadio: [{ required: true, message: '三级抽点不能为空', trigger: 'blur' }],
        mergeType: [{ required: true, message: '上级售卖规则不能为空', trigger: 'blur' }]
      },
      submitting: false
    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.getList()
    categoryTree().then(response => {
      this.categoryList = response.data.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      listDistributionStrategy(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    query() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        type: undefined,
        typeId: undefined,
        radio: undefined,
        firstRadio: undefined,
        secondRadio: undefined,
        thirdRadio: undefined,
        mergeType: undefined
      }
      this.diglogLoadding = false
      this.dialogStatus = 'create'
    },
    updateDialogBtn(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      const temp = {
        id: row.id,
        radio: row.radio / 10.0,
        firstRadio: row.firstRadio / 10.0,
        secondRadio: row.secondRadio / 10.0,
        thirdRadio: row.thirdRadio / 10.0,
        mergeType: row.mergeType
      }
      this.dataForm = Object.assign({}, temp)
    },
    createDialogBtn() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.submitting = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // 校验typeId
          if (this.dataForm.type !== 1 && !this.dataForm.typeId) {
            this.$notify.error({
              title: '失败',
              message: '请关联相应 分类/商品'
            })
            this.submitting = false
            return
          }
          const requestForm = {
            type: this.dataForm.type,
            typeId: this.dataForm.typeId ? this.dataForm.typeId : 0,
            radio: parseInt(this.dataForm.radio * 10),
            firstRadio: parseInt(this.dataForm.firstRadio * 10),
            secondRadio: parseInt(this.dataForm.secondRadio * 10),
            thirdRadio: parseInt(this.dataForm.thirdRadio * 10),
            mergeType: this.dataForm.mergeType
          }
          if (requestForm.firstRadio + requestForm.secondRadio + requestForm.thirdRadio !== 1000) {
            this.$notify.error({
              title: '失败',
              message: '三级代理提点总和必须为100%'
            })
            this.submitting = false
            return
          }
          createDistributionStrategy(requestForm)
            .then(response => {
            // 需要后台返回值
            // this.list.unshift(response.data.data)
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
              this.submitting = false
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submitting = false
            })
        }
      })
    },
    handleUpdate() {
      this.submitting = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const requestForm = {
            id: this.dataForm.id,
            type: this.dataForm.type,
            typeId: this.dataForm.typeId ? this.dataForm.typeId : 0,
            radio: parseInt(this.dataForm.radio * 10),
            firstRadio: parseInt(this.dataForm.firstRadio * 10),
            secondRadio: parseInt(this.dataForm.secondRadio * 10),
            thirdRadio: parseInt(this.dataForm.thirdRadio * 10),
            mergeType: this.dataForm.mergeType
          }
          if (requestForm.firstRadio + requestForm.secondRadio + requestForm.thirdRadio !== 1000) {
            this.$notify.error({
              title: '失败',
              message: '三级代理提点总和必须为100%'
            })
            this.submitting = false
            return
          }
          updateDistributionStrategy(requestForm)
            .then(response => {
            // 需要后台返回值
            // this.list.unshift(response.data.data)
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新信息成功'
              })
              this.submitting = false
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submitting = false
            })
        }
      })
    },
    deleteDistributionBtn(row) {
      this.$confirm('此操作将永久删除该分销用户--' + row.id + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDistributionStrategy(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    searchSpu(e) {
      if (!e) {
        return
      }
      searchGoods(e)
        .then(res => {
          this.searchSpuRes = res.data.data
          const array = []
          if (this.searchSpuRes.length > 0) {
            this.searchSpuRes.forEach(item => {
              array.push({
                value: item.id,
                label: item.title
              })
            })
          }
          this.keyRes = array
        })
    },
    searchSpuChange(e) {
      for (let i = 0; i < this.searchSpuRes.length; i++) {
        if (this.searchSpuRes[i].id === e) {
          this.dataForm.typeId = e
        }
      }
    },
    handleCategoryChange(e) {
      this.dataForm.typeId = e[e.length - 1]
    }
  }
}
</script>
